from flask import Flask, Response
from flask_cors import CORS
from sysfunctions import init_db, client_states
import apifunc as api
from Contest import Contest
import time
app = Flask(__name__, static_folder='./static')
CORS(app)
contest = Contest()
states =client_states()

#region 系统接口
@app.route("/")
def hello():
    return "Back-end running!"
@app.route("/images", methods=["GET"])
def images():
    return api.get_images()

@app.route("/clearAllUsers", methods=['POST'])
def clear_all_users():
    return api.clear_all_users()
#endregion


#region 用户接口

# 事件流
@app.route("/api/stream")
def stream():
    # 为当前客户端生成唯一标识（这里用时间戳示例，实际可用 UUID）
    client_id = str(time.time())
    states.addNew(client_id)
    # 初始化当前客户端的独立状态
    def generate():
        try:
            while True:
                # 仅检查当前客户端的状态
                alert_state, sycdata_state = states.getStates(client_id)
                if alert_state:
                    yield 'data: alert\n\n'
                    states.response(client_id)
                elif sycdata_state:
                    yield 'data: sycdata\n\n'
                    states.response(client_id)
                time.sleep(0.1)  # 降低 CPU 占用，避免线程饿死
        finally:
            # 客户端断开时清理状态
            del states.states[client_id]

    return Response(generate(), mimetype='text/event-stream')

@app.route("/api/register", methods=['POST'])
def register():
    return api.register()

@app.route("/api/login", methods=['POST'])
def login():
    return api.login()

@app.route("/api/sitdown", methods=["POST"])
def sitdown():
    return api.sitdown(contest, states)

@app.route("/api/getUp", methods=['POST'])
def get_up():
    return api.get_up(contest, states)

@app.route("/api/uploadPic", methods=['POST'])
def uploadPic():
    return api.upload_pic()

# 同步对局接口
@app.route('/api/getContest', methods=['POST'])
def get_contest():
    return api.get_contest(contest)

@app.route('/api/getUserInfo', methods=['POST'])
def get_user_info():
    return api.get_user_info()

@app.route('/api/putChess', methods=['POST'])
def put_chess():
    return api.put_chess(contest, states)

@app.route('/api/initContest', methods=['POST'])
def init_contest():
    return api.init_contest(contest, states)
#endregion


if __name__ == "__main__":
    init_db()
    app.run(debug=True, host='0.0.0.0')